package com.weyoung.common.model.dto;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import io.swagger.v3.oas.annotations.media.Schema;
import lombok.Data;

import java.util.Collections;
import java.util.List;
import java.util.function.Function;
import java.util.stream.Collectors;

@Data
@Schema(name = "分页结果")
public class PageDTO<T> {
    @Schema(description = "总记录数")
    private Long total;
    @Schema(description = "总页数")
    private Long pages;
    @Schema(description = "当前页")
    private List<T> list;

    //PO->VO 定义不同泛型
    public static <PO,VO> PageDTO<VO> of(Page<PO> p, Class<VO> clazz) {
        PageDTO<VO> dto = new PageDTO<>();
        //1.总条数
        dto.setTotal(p.getTotal());
        //2.总页数
        dto.setPages(p.getPages());
        //3.当前页数据
        List<PO> records = p.getRecords();
        if (CollUtil.isEmpty(records)){
            dto.setList( Collections.emptyList());
            return dto;
        }
        //4.转换PO->VO
        dto.setList( BeanUtil.copyToList(records,clazz));
        return dto;
    }

    //PO ->VO 自定义转换逻辑作为参数传入
    public static <PO,VO> PageDTO<VO> of(Page<PO> p, Function<PO,VO> converter) {
        PageDTO<VO> dto = new PageDTO<>();
        //1.总条数
        dto.setTotal(p.getTotal());
        //2.总页数
        dto.setPages(p.getPages());
        //3.当前页数据
        List<PO> records = p.getRecords();
        if (CollUtil.isEmpty(records)){
            dto.setList( Collections.emptyList());
            return dto;
        }
        //4.转换stream
        List<VO> collect = records.stream()
                .map(converter)
                .collect(Collectors.toList());
        dto.setList(collect);
        return dto;
    }

    // IPage -> PageDTO
    public static <T> PageDTO<T> of(IPage<T> p) {
        PageDTO<T> dto = new PageDTO<>();
        //1.总条数
        dto.setTotal(p.getTotal());
        //2.总页数
        dto.setPages(p.getPages());
        //3.当前页数据
        dto.setList(p.getRecords());
        return dto;
    }
}